/*
 * This file is part of the Android Dimensions Editor Project: http://code.google.com/p/android-dimension-editor/
 *  
 * Copyright (c) 2013 Rick Falck
 *  
 * This code is licensed under the terms of the Apache License Version 2.0.
 * You may use this code according to the license.
 *
 * The terms of the license can be found in the root directory of this project's repository as well as at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under these Licenses is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See each License for the specific language governing permissions and
 * limitations under that License.
 */
package application;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.TreeMap;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Glow;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import model.DimensFile;
import model.DimensGrid;
import model.FilenameUtils;
import model.ItemName;
import model.ItemValue;
import model.ReturnInfo;
import ContextMenuButton.ContextMenuButton;
import ContextMenuButton.ContextMenuButton.MENU_ITEM;
import MessageBox.MessageBox;
import MessageBox.MessageBoxController.MBOX_TYPE;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.stage.DirectoryChooser;

public class AndroidDimensionsController implements Initializable, ContextMenuButton.Callback {

    // Project button and label
    @FXML
    private ImageView mBTN_Project;

    @FXML
    private Label mLBL_Projectname;

    // Pane control of all ImageView buttons 
    @FXML
    private Pane mHbox_Buttons;

    @FXML
    private ImageView mBTN_New_File;

    @FXML
    private ImageView mBTN_Delete_File;

    @FXML
    private ImageView mBTN_Save_All;

    @FXML
    private ImageView mBTN_Sort;

    @FXML
    private ScrollPane mScrollPane;

    @FXML
    private ScrollPane mScrollPaneTitle;

    @FXML
    private GridPane mGridPane;

    @FXML
    private GridPane mGridPaneTitle;

    // /////////////////////////////////////////////////////////////
    // Menu Bar Items
    // /////////////////////////////////////////////////////////////
    @FXML
    private MenuItem mMenuAbout_About;

    @FXML
    private MenuItem mMenuAbout_Help;

    @FXML
    private MenuItem mMenuEdit_Delete_File;

    @FXML
    private MenuItem mMenuEdit_New_File;

    @FXML
    private MenuItem mMenuEdit_Sort;
    
    @FXML
    private MenuItem mMenuEdit_SetBackup;

    @FXML
    private MenuItem mMenuFile_Exit_NoSave;

    private Tooltip mTipProject;
    private Tooltip mTipNewFolder;
    private Tooltip mTipDeleteFolder;
    private Tooltip mTipSort;
    private Tooltip mTipSaveAll;

    private DropShadow mButtonDropShadow;
    // ////////////////////////////////////////////////////
    // Other Member Data
    // ////////////////////////////////////////////////////
    private DimensGrid mDimensGrid;

    public static Stage primaryStage;
    private boolean mCloseListenerCreated = false;

    private ArrayList<ContextMenuButton> mContextButtons;

    private final String mTooltipBackgroundStyle = "-fx-background-color: #ffffc0;";

    // Fields for saving the user's data
    private final String mProjectPre = "PROJECT:";
    private final String mBackupPre = "BACKUP:";
    private String mProjectPath = null;
    private String mBackupPath = null;
    private final String sUserFilename = "UserPreferences.txt";

    public AndroidDimensionsController() {

    }

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {

        mButtonDropShadow = new DropShadow();
        mButtonDropShadow.setRadius(5.0);
        mButtonDropShadow.setOffsetX(3.0);
        mButtonDropShadow.setOffsetY(3.0);
        mButtonDropShadow.setColor(Color.color(0.3, 0.4, 0.4));

        mTipProject = new Tooltip("Open a project's dimens files");
        mTipProject.setStyle(mTooltipBackgroundStyle);
        Tooltip.install(mBTN_Project, mTipProject);
        mBTN_Project.setEffect(mButtonDropShadow);
        mBTN_Project.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (e.getEventType() == MouseEvent.MOUSE_CLICKED) {
                    if (e.getButton() == MouseButton.PRIMARY) {
                        OnBtnProject();
                    }
                } else if (e.getEventType() == MouseEvent.MOUSE_ENTERED) {
                    showButoonMouseEnteredEffect(mBTN_Project);
                } else if (e.getEventType() == MouseEvent.MOUSE_EXITED) {
                    mBTN_Project.setEffect(mButtonDropShadow);
                }
            }
        });

        mTipNewFolder = new Tooltip("Create a new values folder and dimens file ");
        mTipNewFolder.setStyle(mTooltipBackgroundStyle);
        Tooltip.install(mBTN_New_File, mTipNewFolder);
        mBTN_New_File.setEffect(mButtonDropShadow);
        mBTN_New_File.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (e.getEventType() == MouseEvent.MOUSE_CLICKED) {
                    if (e.getButton() == MouseButton.PRIMARY) {
                        OnBtnNewFile();
                    }
                } else if (e.getEventType() == MouseEvent.MOUSE_ENTERED) {
                    showButoonMouseEnteredEffect(mBTN_New_File);
                } else if (e.getEventType() == MouseEvent.MOUSE_EXITED) {
                    mBTN_New_File.setEffect(mButtonDropShadow);
                }
            }
        });

        mTipDeleteFolder = new Tooltip("Delete a dimens folder/file");
        mTipDeleteFolder.setStyle(mTooltipBackgroundStyle);
        Tooltip.install(mBTN_Delete_File, mTipDeleteFolder);
        mBTN_Delete_File.setEffect(mButtonDropShadow);
        mBTN_Delete_File.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (e.getEventType() == MouseEvent.MOUSE_CLICKED) {
                    if (e.getButton() == MouseButton.PRIMARY) {
                        OnBtnDeleteFile();
                    }
                } else if (e.getEventType() == MouseEvent.MOUSE_ENTERED) {
                    showButoonMouseEnteredEffect(mBTN_Delete_File);
                } else if (e.getEventType() == MouseEvent.MOUSE_EXITED) {
                    mBTN_Delete_File.setEffect(mButtonDropShadow);
                }
            }
        });

        mMenuFile_Exit_NoSave.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                Platform.exit();
            }
        });

        mMenuEdit_New_File.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                OnBtnNewFile();
            }
        });

        mMenuEdit_Delete_File.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                OnBtnDeleteFile();
            }
        });

        mMenuEdit_Sort.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                OnBtnSort();
            }
        });
        
        mMenuEdit_SetBackup.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                OnBtnSetBackup();
            }
        });

        mMenuAbout_Help.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                OnBtnHelp();
            }
        });

        mTipSaveAll = new Tooltip("Save all modified files");
        mTipSaveAll.setStyle(mTooltipBackgroundStyle);
        Tooltip.install(mBTN_Save_All, mTipSaveAll);
        mBTN_Save_All.setEffect(mButtonDropShadow);
        mBTN_Save_All.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (e.getEventType() == MouseEvent.MOUSE_CLICKED) {
                    if (e.getButton() == MouseButton.PRIMARY) {
                        OnBtnSaveAll();
                    }
                } else if (e.getEventType() == MouseEvent.MOUSE_ENTERED) {
                    showButoonMouseEnteredEffect(mBTN_Save_All);
                } else if (e.getEventType() == MouseEvent.MOUSE_EXITED) {
                    mBTN_Save_All.setEffect(mButtonDropShadow);
                }
            }
        });

        mTipSort = new Tooltip("Sort all items (and comments)");
        mTipSort.setStyle(mTooltipBackgroundStyle);
        Tooltip.install(mBTN_Sort, mTipSort);
        mBTN_Sort.setEffect(mButtonDropShadow);
        mBTN_Sort.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (e.getEventType() == MouseEvent.MOUSE_CLICKED) {
                    OnBtnSort();
                } else if (e.getEventType() == MouseEvent.MOUSE_ENTERED) {
                    showButoonMouseEnteredEffect(mBTN_Sort);
                } else if (e.getEventType() == MouseEvent.MOUSE_EXITED) {
                    mBTN_Sort.setEffect(mButtonDropShadow);
                }
            }
        });

        mHbox_Buttons.setDisable(true);

        mScrollPane.setContent(mGridPane);
        mScrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        mScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);

        mScrollPaneTitle.setContent(mGridPaneTitle);
        mScrollPaneTitle.setHbarPolicy(ScrollBarPolicy.NEVER);
        mScrollPaneTitle.setVbarPolicy(ScrollBarPolicy.ALWAYS);

        mScrollPane.hvalueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> ov,
                    Number old_val, Number new_val) {
                mScrollPaneTitle.setHvalue(new_val.doubleValue());
            }
        });

        getUserData();
    }

    protected void getUserData() {
        File userFile = new File(sUserFilename);
        if (userFile.exists()) {
            BufferedReader in = null;
            try {
                FileReader rdr = new FileReader(userFile);
                in = new BufferedReader(rdr);
                String strIn = null;
                do {
                    strIn = in.readLine();
                    
                    if (strIn != null) {
                        int pos = strIn.indexOf(":");
                        if (pos > 0) {
                            String path = strIn.substring(pos + 1).trim();
                            
                            if (strIn.startsWith(mProjectPre)) {
                                mProjectPath = path;
                            } else if (strIn.startsWith(mBackupPre)) {
                                mBackupPath = path;
                            }
                        }
                    }
                } while (strIn != null);
            } catch (IOException e) {
                mProjectPath = null;
                mBackupPath = null;
                MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                        "Failed to read " + sUserFilename, null);
                Logger.getLogger(AndroidDimensionsController.class.getName()).log(Level.SEVERE, "getUserData()", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Logger.getLogger(AndroidDimensionsController.class.getName()).log(Level.SEVERE, "getUserData() - in.close()", ex);
                    }
                }
            }
        }
    }

    protected void saveUserData() {
        File userFile = new File(this.sUserFilename);
        PrintWriter pr = null;
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(userFile));
            pr = new PrintWriter(out);
            pr.println(mProjectPre + mProjectPath);
            if (mBackupPath != null) {
                pr.println(mBackupPre + mBackupPath);
            }
        } catch (IOException e) {
            mProjectPath = null;
        } finally {
            if (pr != null) {
                pr.close();
            }
        }
    }
    
    protected void OnBtnSetBackup() {
        getUserBackupPath();
        
        if (mBackupPath != null) {
            saveUserData();
        }
        
    }

    protected void getUserBackupPath() {
        DirectoryChooser dc = new DirectoryChooser();
        dc.setInitialDirectory(new File(System.getProperty("user.dir")));
        dc.setTitle("Select/Create Backup Directory");

        File bdir = dc.showDialog(mBTN_Project.getScene().getWindow());

        if (bdir != null) {
            mBackupPath = bdir.getAbsolutePath();
        } else {
            mBackupPath = null;
            MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                    "No directory selected.\nFiles will not be backed up!", null);
        }

    }

    protected void showButoonMouseEnteredEffect(ImageView btn) {
        btn.setEffect(new Glow(0.6));
    }

    public void OnBtnProject() {
        if (mBackupPath == null) {
            getUserBackupPath();
        }
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Choose one dimens.xml File");

        // Extension filter
        FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter(
                "XML files (*.xml)", "*.xml");
        fileChooser.getExtensionFilters().addAll(extentionFilter);
        File userFileDir;
        // Set to user directory
        if (mProjectPath == null) {
            userFileDir = new File(System.getProperty("user.dir"));
        } else {
            userFileDir = new File(mProjectPath);
        }

        fileChooser.setInitialDirectory(userFileDir);

        // Choose the file
        File chosenFile = fileChooser.showOpenDialog(mBTN_Project.getScene().getWindow());

        if (chosenFile != null && chosenFile.getName() != null) {
            DimensGrid.DIMENS_FILENAME = chosenFile.getName();

            String pathToFile = FilenameUtils.getFullPathNoEndSeparator(chosenFile
                    .getAbsolutePath());
            DimensGrid.DIMENS_FOLDER_PREFIX = FilenameUtils.getBaseName(pathToFile);
            int lsep = FilenameUtils.indexOfLastSeparator(pathToFile);

            String labelTextfile = new File(pathToFile.substring(0, lsep)).getParent();
            mLBL_Projectname.setText(labelTextfile);

            if (mProjectPath == null || !mProjectPath.equalsIgnoreCase(labelTextfile)) {
                mProjectPath = labelTextfile;
                saveUserData();
            }

            String pathToResWithSeparator = pathToFile.substring(0, lsep + 1);

            File fPatyhToRes = new File(pathToResWithSeparator);
            String[] dirs = fPatyhToRes.list();

            // TreeMap of <valuesxxx, File>
            Map<String, File> dimensFiles = new TreeMap<>();

            for (String dir : dirs) {
                if (dir.contains("values")) {
                    File f = new File(pathToResWithSeparator + dir, DimensGrid.DIMENS_FILENAME);
                    if (f.exists()) {
                        dimensFiles.put(dir, f);
                    }
                }
            }

            mDimensGrid = new DimensGrid(fPatyhToRes);
            ReturnInfo ret;
            if (mBackupPath != null) {
                ret = mDimensGrid.backup(mBackupPath, dimensFiles);

                if (!ret.isSuccess()) {
                    MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                            "Backup Failed: " + ret.getErrorType().name()
                            + System.lineSeparator() + ret.getErrorMessage(), null);
                    return;
                }
            }
            ret = mDimensGrid.readFiles(dimensFiles);
            if (!ret.isSuccess()) {
                MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                        "Read Failed: " + ret.getErrorType().name()
                        + System.lineSeparator() + ret.getErrorMessage(), null);
                return;
            }

            mContextButtons = new ArrayList<>();

            fillTable();

            mHbox_Buttons.setDisable(false);

            if (!mCloseListenerCreated) {
                mCloseListenerCreated = true;
                primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                    @Override
                    public void handle(WindowEvent we) {
                        ReturnInfo ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.CONFIRMATION, "Exit Application?", null);
                        if (!ret.isSuccess()) {
                            we.consume();
                        }
                    }
                });
            }
        }
    }

    private void fillTable() {
        mGridPane.getChildren().clear();
        mGridPane.getColumnConstraints().clear();
        mGridPane.getRowConstraints().clear();

        // mGridPane.setGridLinesVisible(true);
        mGridPane.setVgap(1);
        mGridPane.setHgap(1);

        mGridPaneTitle.getChildren().clear();
        mGridPaneTitle.getColumnConstraints().clear();
        mGridPaneTitle.getRowConstraints().clear();

        // mGridPane.setGridLinesVisible(true);
        mGridPaneTitle.setVgap(1);
        mGridPaneTitle.setHgap(1);

        // The Delete Buttons column
        ColumnConstraints col1 = new ColumnConstraints();
        col1.setFillWidth(true);
        col1.setHalignment(HPos.CENTER);
        col1.setHgrow(Priority.NEVER);
        col1.setMinWidth(26.0);
        col1.setPrefWidth(26.0);

        int maxNameLength = mDimensGrid.getLongestNameLength();
        double col2width = (double) maxNameLength * 8.0f;
        // The column of item names
        ColumnConstraints col2 = new ColumnConstraints();
        col2.setFillWidth(true);
        col2.setHalignment(HPos.LEFT);
        col2.setHgrow(Priority.NEVER);
        col2.setMinWidth(col2width);
        col2.setPrefWidth(col2width);

        mGridPane.getColumnConstraints().add(col1);
        mGridPane.getColumnConstraints().add(col2);
        mGridPaneTitle.getColumnConstraints().add(col1);
        mGridPaneTitle.getColumnConstraints().add(col2);

        RowConstraints row1 = new RowConstraints();
        row1.setFillHeight(true);
        row1.setValignment(VPos.CENTER);
        row1.setVgrow(Priority.NEVER);
        row1.setMinHeight(32);
        row1.setPrefHeight(32);

        mGridPane.getRowConstraints().add(row1);
        mGridPaneTitle.getRowConstraints().add(row1);

        // Add Item Buttons and item names to columns 0 and 1
        int row = 0;
        for (ItemName name : mDimensGrid.getItemNameList()) {
            ContextMenuButton menuButton = null;

            for (ContextMenuButton mButton : mContextButtons) {
                if (mButton.getMyItem().equals(name)) {
                    menuButton = mButton;
                    break;
                }
            }
            if (menuButton == null) {
                menuButton = new ContextMenuButton(this, name);
                mContextButtons.add(menuButton);
            }
            mGridPane.add(menuButton, 0, row);
            mGridPane.add(name, 1, row++);
            mGridPane.getRowConstraints().add(row1);
        }

        // Fill row 0 with the values folder names
        int col = 2;
        for (DimensFile file : mDimensGrid.getAllFiles()) {
//			TextField label = new TextField(file.getFolderName());
//			label.setEditable(false);
//			label.getStylesheets().add("application/application.css");
//			label.getStyleClass().add("valuerowitem");

            TextField label2 = new TextField(file.getFolderName());
            label2.setEditable(false);
            label2.getStylesheets().add("application/application.css");
            label2.getStyleClass().add("valuerowitem");

            //mGridPane.add(label, col, 0);
            mGridPaneTitle.add(label2, col, 0);
            int labelSize = file.getFolderName().length();

            double colwidth = (double) labelSize * 9.0f;

            ColumnConstraints thisCol = new ColumnConstraints();
            thisCol.setFillWidth(true);
            thisCol.setHalignment(HPos.CENTER);
            thisCol.setHgrow(Priority.NEVER);
            thisCol.setMinWidth(colwidth);
            thisCol.setPrefWidth(colwidth);
            mGridPane.getColumnConstraints().add(thisCol);
            mGridPaneTitle.getColumnConstraints().add(thisCol);

            // Fill the values for the current file (column)
            for (ItemName iName : file.getItemNames()) {
                // if (!iName.isComment()) {
                ItemValue value = file.getValue(iName);
                row = mDimensGrid.getItemNameIndex(iName);

                try {
                    mGridPane.add(value, col, row);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // }
            }
            col++;
        }

        mGridPane.layout();
        mGridPaneTitle.layout();
    }

    protected void OnBtnNewFile() {
        ReturnInfo ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.GET_USER_TEXT, "Enter New Values Folder Name", null);
        if (ret.isSuccess()) {
            if (ret.getOtherInfo() == null
                    || !ret.getOtherInfo().startsWith(DimensGrid.DIMENS_FOLDER_PREFIX)) {
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, "Invalid folder name.  It must start with "
                        + DimensGrid.DIMENS_FOLDER_PREFIX, null);
            } else if (mDimensGrid.folderExists(ret.getOtherInfo())) {
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, "Folder already exists", null);
            } else {
                mDimensGrid.addNewFile(MessageBox.mUserText);
                fillTable();
            }
        } else {
            if (ret.getErrorMessage() != null) {
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, ret.getErrorMessage(), null);
            }
        }
    }

    protected void OnBtnSaveAll() {
        ReturnInfo ret = mDimensGrid.saveAll();
        if (ret.isSuccess()) {
            MessageBox.showPopUp(primaryStage, MBOX_TYPE.INFORMATION, "Files Saved!", null);
        } else {
            MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                    "Save Failed: " + ret.getErrorType().name() + System.lineSeparator()
                    + ret.getErrorMessage(), null);
        }
    }

    protected void OnBtnSort() {
        mDimensGrid.sort();
        fillTable();
    }

    protected void OnBtnDeleteFile() {
        ReturnInfo ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.GET_USER_SELECTION,
                "Select Values Folder to Delete File From", mDimensGrid.getFolderNames());
        if (ret.isSuccess()) {
            mDimensGrid.deleteFile(MessageBox.mComboBoxSelectedText);
            fillTable();
        }
    }

    private void OnBtnHelp() {
        MessageBox.showPopUp(primaryStage, MBOX_TYPE.HELP, null, null);
    }

    @Override
    public void onMenuItemSelected(MENU_ITEM menuItem, ItemName selectedItem) {
        ReturnInfo ret;
        switch (menuItem) {
            case DELETE:
                mDimensGrid.deleteItemName(selectedItem);
                break;
            case INSERT_ABOVE:
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.GET_USER_TEXT, "Enter New Item Name", null);
                if (ret.isSuccess()) {
                    if (ret.getOtherInfo() == null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, "No Name Entered", null);
                    } else if (mDimensGrid.NameItemExists(ret.getOtherInfo())) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                                "Item Name already exists " + ret.getOtherInfo(), null);
                    } else {
                        mDimensGrid.addNewNameItem(selectedItem, MessageBox.mUserText, true);
                        fillTable();
                    }
                } else {
                    if (ret.getErrorMessage() != null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, ret.getErrorMessage(), null);
                    }
                }
                break;
            case INSERT_BELOW:
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.GET_USER_TEXT, "Enter New Item Name", null);
                if (ret.isSuccess()) {
                    if (ret.getOtherInfo() == null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, "No Name Entered", null);
                    } else if (mDimensGrid.NameItemExists(ret.getOtherInfo())) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                                "Item Name already exists " + ret.getOtherInfo(), null);
                    } else {
                        mDimensGrid.addNewNameItem(selectedItem, MessageBox.mUserText, false);
                        fillTable();
                    }
                } else {
                    if (ret.getErrorMessage() != null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, ret.getErrorMessage(), null);
                    }
                }
                break;
            case INSERT_COMMENT:
                ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.GET_USER_TEXT, "Enter New Comment (without XML tags)", null);
                if (ret.isSuccess()) {
                    if (ret.getOtherInfo() == null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, "No Name Entered", null);
                    } else if (mDimensGrid.NameItemExists(ret.getOtherInfo())) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR,
                                "Item Name already exists " + ret.getOtherInfo(), null);
                    } else {
                        mDimensGrid.addNewCommentItem(selectedItem, MessageBox.mUserText);
                        fillTable();
                    }
                } else {
                    if (ret.getErrorMessage() != null) {
                        ret = MessageBox.showPopUp(primaryStage, MBOX_TYPE.ERROR, ret.getErrorMessage(), null);
                    }
                }
                break;
            case MOVE_DOWN:
                mDimensGrid.moveItemDown(selectedItem);
                break;
            case MOVE_UP:
                mDimensGrid.moveItemUp(selectedItem);
                break;
            case DEFAULT:
                break;
        }
        fillTable();

    }

}
